package net.zjitc.service.Impl;

import com.google.gson.Gson;
import java.util.List;
import net.zjitc.Utils.CommonUtils;
import net.zjitc.dao.AdminDao;
import net.zjitc.dao.ProductDao;
import net.zjitc.dao.UserCartDao;
import net.zjitc.pojo.CartItem;
import net.zjitc.pojo.Product;
import net.zjitc.pojo.User;
import net.zjitc.redis.Redis;
import net.zjitc.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/15 15:38
 * @description:
 */
@Service
public class CartServiceImpl implements CartService {
  @Autowired
  private UserCartDao userCartDao;
  @Autowired
  private ProductDao productDao;
  @Autowired
  private AdminDao adminDao;
  @Autowired
  private Redis redis;
  @Override
  public List<CartItem> findByUid(Integer uid) {
    List<CartItem> list =userCartDao.findByUid(uid);
    for (CartItem c: list){
      Product product = productDao.findByPid(c.getPid());
      User user =adminDao.findByUid(c.getUid());
      c.setProduct(product);
      c.setUser(user);
    }
    return list;
  }

  @Override
  public int add(CartItem cartItem) {
    CartItem ds_cartItem=userCartDao.findByUidAndPid(cartItem.getProduct().getPid(),cartItem.getUser().getUid());
    //判断是否为空
    if (ds_cartItem==null){
      //新增一条
      cartItem.setCartid(CommonUtils.uuid());//用uuid设置主键
      return userCartDao.add(cartItem);
    }else {
      //数据库中有此商品，则修改数量
      int quantity=cartItem.getQuantity()+ds_cartItem.getQuantity();
      ds_cartItem.setQuantity(quantity);
      //更新
      return userCartDao.update(ds_cartItem);
    }
  }

  @Override
  public String removeCart(String cartid) {
    //从数据库中删除所选的字段
    userCartDao.DeleteUser(cartid);
    Gson gson =new Gson();
    //更新Redis中的缓存数据
    List<CartItem> cartItems =userCartDao.findAll();
    String cartlist = gson.toJson(cartItems);
    redis.set("cartitem",cartlist);
    return null;
  }

  @Override
  public Integer clearCart(Integer uid) {
    userCartDao.clearCart(uid);
    Gson gson =new Gson();
    List<CartItem> cartItems =userCartDao.findAll();
    String cartlist = gson.toJson(cartItems);
    redis.set("cartitem",cartlist);
    return null;
  }
}
